<template>
  <div class="index">
    <span class="last">
          当前剩余{{ infoData.data.presentPokerNum }}张
    </span>
    <button v-if="infoData.data.presentPokerNum===0" @click="onemore">
      原班人马
    </button>
    <button v-if="infoData.data.presentPokerNum===0" @click="reset">
      重置玩家
    </button>
    <button @click="getPoker" :class="{none:infoData.data.presentPokerNum===0}">
      摸牌
    </button>
    <span v-if="showPokerDesc">
      <span :class="isred(lastgetPoker)?'redPoker':'blackPoker'" style="font-size: 20px">{{ lastgetPoker }}</span>
      <span style="font-size: 15px">{{ pokerDesc }}</span>
    </span>

    <table>
      <tr>
        <td>
          <table>
            <tr v-for="(colsnum, colindex) in Math.ceil(infoData.data.infoList.length/2)" v-bind:key="colsnum">
              <template v-for="(value, index) in infoData.data.infoList">
                <td class="playerinfo"
                  :style="{background: (index+1===infoData.data.now)?'yellow':''}"
                  v-if="Math.floor(index/2)===colindex"  v-bind:key="index">
                <table>
                  <tr class="first">
                    <td rowspan="3" class="firsttd">
                      {{ index + 1 }} {{ value.name }}
                      <span class="sister" v-if="index+1==infoData.data.sister">小姐</span>
                      <p></p>
                      <button @click="drinkData(index + 1, 1, 0)">欠着</button>
                      <button @click="drinkData(index + 1, 1, 1)">喝了</button>
                      <button @click="drinkData(index + 1, 2, 1)">还账</button>
                    </td>
                    <table>
                      <tr v-for="(num, numindex) in Math.ceil(value.pokerList.length/3)" v-bind:key="num">
                      <template v-for="(poker, pokerindex) in value.pokerList">
                        <td v-bind:key="poker"
                            v-if="Math.floor(pokerindex/3)===numindex" class="poker"
                            :class="isred(poker)?'redPoker':'blackPoker'" @click="usePoker(poker)">{{ poker }}
                        </td>
                      </template> 
                      </tr>
                    </table>
                  </tr>
                  <tr class="second">
                  </tr>
                  <tr class="third">
                  </tr>
                  <tr class="fouth">
                    <div class="fouthtd">
                      <td class="fouthtd" clospan="4">
                        欠{{ value.needDrinkNum }} 杯， 已喝 {{ value.hasDrinkedNum }} 杯
                      </td>
                    </div>
                  </tr>
                </table>
              </td>
              </template>
            </tr>
          </table>
        </td>
        <td class="gamenametd">
          <div class="gamename">
            <span>扭一扭</span>
            <span style="font-size: 35px">(视频区域)</span>
          </div>
        </td>
      </tr>
    </table>
    <router-view/>
  </div>
</template>

<script>
import request from '@/utils/request'

export default {
  name: 'index',
  data() {
    return {
      data: [],
      infoData: {data: {infoList: [], lastgetPoker: '', presentPokerNum: 0}},
      lastgetPoker: '',
      pokerDesc: '',
      ws: null,
      idForWebsocket: null,
      showPokerDesc: true
    }
  },
  methods: {
    async getinfo() {
      let res = await request({
        url: 'home/getInfo',
        headers: {
          isToken: true
        },
        method: 'get',
      })
      this.infoData = res
      this.lastgetPoker = this.infoData.data.lastgetPoker
      this.pokerDesc = this.infoData.data.pokerDesc
    },
    async getPoker() {
      let res = await request({
        url: 'home/getPoker',
        headers: {
          isToken: true
        },
        method: 'get',
      })
      if (res.code !== 200) {
        alert(res.msg)
      }
      this.showPokerDesc = true
    },
    async drinkData(playerNum, drinkType, hasDrinked) {
      let res = await request({
        url: 'home/drinkData',
        headers: {
          isToken: true
        },
        method: 'post',
        data: {playerNum: playerNum, drinkType: drinkType, hasDrinked: hasDrinked}
      })
      if (res.code !== 200) {
        alert(res.msg)
      }
    },
    async onemore() {
      let res = await request({
        url: 'home/onemore',
        headers: {
          isToken: true
        },
        method: 'get',
      })
      this.lastgetPoker = ''
      if (res.code === 200) {
        this.getinfo()
        this.showPokerDesc = false
      }
      alert(res.msg)
    },
    async usePoker(poker) {
      let res = await request({
        url: 'home/usePoker',
        headers: {
          isToken: true
        },
        method: 'post',
        data: {poker: poker}
      })
      if (res.code !== 200) {
        alert(res.msg)
      }
    },
    isred(poker) {
      if (poker != null && (poker.split('')[0] === '♦' || poker.split('')[0] === '♥')) {
        return true
      }
      return false
    },
    reset() {
      this.$router.push({ name: 'Index', params: { index: '3' }})
    },
    fluseData() {
      this.getinfo()
    },
    initWebsocket() {
      // 建立socket通道
      // process.env.VUE_APP_URL为服务端地址
      // code为自定义的参数，主要是用于服务端标识当前会话是哪个用户
      this.ws = new WebSocket(
        // 部署服务器时可结合nginx代理使用
        'ws://' + process.env.VUE_APP_BASE_IP + '/websocket'
      )
      // socket连接成功后的回调函数
      if (this.ws) {
        this.ws.onopen = x => {
          console.log('连接成功')
          console.log('连接信息：', x)
        }
      }
    },
    websocket() {
      this.initWebsocket()
      // 若项目中没有使用nginx转发请求则忽略这步
      // 设置定时器，每过55秒传一次数据
      // 以防长时间不通信被nginx自动关闭会话
      // 也可以通过修改nginx配置文件延长关闭时间
      // id用于结束这个轮巡任务
      let id = setInterval(() => {
        this.keepAlive(this.ws)
      }, 55000)
      // 接收来自服务端消息的回调函数
      // fluseData() 为自定义的数据刷新函数
      this.ws.onmessage = evt => {
        console.log('已接收来自后台的消息：', evt)
        // 刷新数据
        this.fluseData()
      }
      // 关闭socket的回调函数
      this.ws.onclose = function () {
        // 结束轮巡，不这样操作，会出现在浏览器返回前进后（返回前进触发了老连接的关闭，新连接的产生），还一直轮巡一个已经不存在的连接
        clearInterval(id)
        // 关闭 websocket
        console.log('连接已关闭...')
      }
      // 路由跳转时结束websocket链接
      this.$router.afterEach(function () {
        this.ws.close()
      })
    },
    // 持续向后台发送消息，用于维护socket通道不被nginx关闭
    keepAlive(webSocket) {
      if (webSocket) {
        console.log('当前webSocket信息:', webSocket)
        if (webSocket.readyState === webSocket.OPEN) {
          webSocket.send('心跳')
        } else {
          console.log('心跳检测失败，重新连接')
          webSocket.onopen = x => {
            console.log('连接成功')
            console.log('连接信息：', x)
          }
        }
      } else {
        console.log('websocket连接关闭，无法心跳！！')
      }
    }
  },
  // 钩子函数，进入页面自动执行
  mounted: function () {
    console.log(process.env)
    if (this.ws) {
      console.log('ws存在，不需要重新创建')
    } else {
      this.idForWebsocket = new Date().valueOf()
      this.websocket()
      // this.getinfo()
      // async function () {
      //   await this.getinfo()
      //   // 每秒执行一次
      //   setInterval(() => {
      //     setTimeout(this.getinfo, 0)
      //   }, 1000 * 1)
      // }
    }
  },
  beforeDestroy() {
    this.ws.close()
  }
}
</script>

<style>
.index {
  text-align: left;
  color: coral;
}

.last {
  /*padding: 50px;*/
  text-align: center;
  font-size: 20px;
  color: coral;
}

.none {
  color: gray;
}

.gamename {
  font-size: 50px;
  text-align: center;
  font-style: inherit;
  text-shadow: 3px 3px 3px yellow;
  color: dodgerblue;
}

.gamenametd {
  width: 60%;
  text-align: center;
}

.redPoker {
  color: red;
  background: white;
}

.blackPoker {
  color: black;
  background: white;
}

.poker {
  border: 1px solid black;
  /*扑克牌3d渐变效果，后续优化*/
  /*  border-top:3px solid black;*/
  /*  border-bottom:3px solid gray;*/
  /*  border-left:3px solid black;*/
  /*  border-right:3px solid gray;*/
}

.playerinfo {
  padding: 5px;
  margin: 5px;
  border: 1px solid black;
  width: 40%;
  height: 150px;
  font-size: 20px;
  background: aqua;
}

.sister {
  font-size: 16px;
  color: white;
  /*font-weight: bolder;*/
  border: 1px solid yellow;
  text-align: center;
  background: red;
  padding: 3px;
}

ul {
  list-style: none;
}

/*加边框，方便调试样式*/
/*td {*/
/*  border: 1px solid black;*/
/*}*/

.fouth {
  font-size: 15px;
}

.fouthtd {
  width: 200px;
}

.firsttd {
  width: 50px;
  height: 50px;
}
</style>
